<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Java语言高级:多线程 | Baby李の小窝</title><meta name="keywords" content="学习笔记,语言相关,Java"><meta name="author" content="Baby李"><meta name="copyright" content="Baby李"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="关于Java多线程的学习笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="Java语言高级:多线程">
<meta property="og:url" content="http://example.com/2021/02/22/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E5%A4%9A%E7%BA%BF%E7%A8%8B/index.html">
<meta property="og:site_name" content="Baby李の小窝">
<meta property="og:description" content="关于Java多线程的学习笔记">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://www.helloimg.com/images/2021/02/22/BcV0c0.png">
<meta property="article:published_time" content="2021-02-22T09:53:55.000Z">
<meta property="article:modified_time" content="2021-02-22T10:31:10.868Z">
<meta property="article:author" content="Baby李">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="语言相关">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://www.helloimg.com/images/2021/02/22/BcV0c0.png"><link rel="shortcut icon" href="/img/%E6%A3%92%E5%86%B0.png"><link rel="canonical" href="http://example.com/2021/02/22/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E5%A4%9A%E7%BA%BF%E7%A8%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2021-02-22 18:31:10'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="//at.alicdn.com/t/font_2382062_1cihbg7iovj.css"><link rel="stylesheet" href="/css/self.css"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">4</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">1</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 番剧</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友人帐</span></a></div><div class="menus_item"><a class="site-page" href="/saysay/"><i class="fa-fw iconfont icon-wenda"></i><span> 说说</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://www.helloimg.com/images/2021/02/22/BcV0c0.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Baby李の小窝</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page" href="/bangumis/"><i class="fa-fw fas fa-video"></i><span> 番剧</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友人帐</span></a></div><div class="menus_item"><a class="site-page" href="/saysay/"><i class="fa-fw iconfont icon-wenda"></i><span> 说说</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java语言高级:多线程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-22T09:53:55.000Z" title="发表于 2021-02-22 17:53:55">2021-02-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-02-22T10:31:10.868Z" title="更新于 2021-02-22 18:31:10">2021-02-22</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="一、多线程的创建"><a href="#一、多线程的创建" class="headerlink" title="一、多线程的创建"></a>一、多线程的创建</h2><h3 id="方式1：继承于Thread类"><a href="#方式1：继承于Thread类" class="headerlink" title="方式1：继承于Thread类"></a>方式1：继承于Thread类</h3><ol>
<li>创建一个继承于 Thread 类的子类</li>
<li>重写 Thread 类的 run()  —— 将此线程执行的操作声明在 run()中</li>
<li>创建 Thread 类的子类对象</li>
<li>通过此对象调用 start() ：① 启动当前线程；②调用当前线程的 run()</li>
</ol>
<h4 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 例子：遍历100以内所有的偶数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1.创建一个继承于Thread类的子类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 2.重写Thread类的run()</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.run();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (i % <span class="number">2</span> == <span class="number">0</span>) &#123;</span><br><span class="line">                System.out.println(i);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 3.创建Thread类的子类对象</span></span><br><span class="line">        MyThread myThread = <span class="keyword">new</span> MyThread();</span><br><span class="line">        <span class="comment">// 4.通过此对象调用start()</span></span><br><span class="line">        myThread.start();</span><br><span class="line">        <span class="comment">// 如下操作仍然是在main线程中执行的</span></span><br><span class="line">        System.out.println(<span class="string">&quot;Hello,World&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建Thread类的匿名子类的方式</span></span><br><span class="line">        <span class="keyword">new</span> Thread() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="keyword">super</span>.run();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;.start();</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="问题一"><a href="#问题一" class="headerlink" title="问题一"></a>问题一</h4><p>我们不能直接通过调用 run() 的方式启动线程</p>
<h4 id="问题二"><a href="#问题二" class="headerlink" title="问题二"></a>问题二</h4><p>再启动一个线程，遍历100以内的偶数。不可以还让已经start()的线程去执行，否则会抛出IllegalThreadStateException异常<br>我们需要重新创建一个线程的对象，去调用start()</p>
<h3 id="Thread类中的常用方法"><a href="#Thread类中的常用方法" class="headerlink" title="Thread类中的常用方法"></a>Thread类中的常用方法</h3><ol>
<li>start()：启动当前线程；调用当前线程的run()</li>
<li>run()：通常需要重写Thread类中的此方法，将创建的线程要执行的操作声明在此方法中</li>
<li>currentThread()：静态方法，返回执行当前代码的线程</li>
<li>getName()：获取当前线程的名字</li>
<li>setName()：设置当前线程的名字</li>
<li>yield()：释放当前cpu的执行权</li>
<li>join()：在线程a中调用线程b的 join() ，此时线程a就进入阻塞状态，直到线程b完全被执行以后，线程a才结束阻塞状态</li>
<li><del>stop()</del>：<strong>已过时</strong>。当执行此方法时，强制结束当前线程</li>
<li>sleep(long millis)：让当前线程“睡眠”指定的millis毫秒。在指定的millis毫秒时间内，当前线程是阻塞状态</li>
<li>isAlive()：判断当前线程是否存活</li>
</ol>
<hr>
<h3 id="方式2：实现Runnable接口"><a href="#方式2：实现Runnable接口" class="headerlink" title="方式2：实现Runnable接口"></a>方式2：实现Runnable接口</h3><ol>
<li>创建一个实现了 Runnable接口 的类</li>
<li>实现类去实现Runnable中的抽象方法：run()</li>
<li>创建实现类的对象</li>
<li>将此对象作为参数传递到Thread类的构造器中，创建Thread类的对象</li>
<li>通过Thread类的对象调用start()</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  例子：遍历100以内所有的偶数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1. 创建一个实现了 Runnable接口 的类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MTest</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 2. 实现类去实现Runnable中的抽象方法：run()</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (i % <span class="number">2</span> == <span class="number">0</span>) &#123;</span><br><span class="line">                System.out.println(i);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MThread</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 3. 创建实现类的对象</span></span><br><span class="line">        MTest mTest = <span class="keyword">new</span> MTest();</span><br><span class="line">        <span class="comment">// 4. 将此对象作为参数传递到Thread类的构造器中，创建Thread类的对象</span></span><br><span class="line">        Thread thread = <span class="keyword">new</span> Thread(mTest);</span><br><span class="line">        <span class="comment">// 5. 通过Thread类的对象调用start()</span></span><br><span class="line">        thread.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h3 id="以上两种方式的比较"><a href="#以上两种方式的比较" class="headerlink" title="以上两种方式的比较"></a>以上两种方式的比较</h3><p>开发中优先选择：实现Runnable接口的方式</p>
<p>原因：</p>
<ol>
<li>实现接口的方式没有类的单继承性的局限性</li>
<li>实现的方式更适合来处理多个线程有共享数据的情况</li>
</ol>
<p>联系：Thread类本身实现了Runnable接口</p>
<p>相同点：两种方式都需要重写run()，将线程要的逻辑声明在run()中</p>
<h3 id="lt-——JDK-5-0新增线程创建方式——-gt"><a href="#lt-——JDK-5-0新增线程创建方式——-gt" class="headerlink" title="&lt;——JDK 5.0新增线程创建方式——&gt;"></a>&lt;——JDK 5.0新增线程创建方式——&gt;</h3><h3 id="方式3：实现Callable接口"><a href="#方式3：实现Callable接口" class="headerlink" title="方式3：实现Callable接口"></a>方式3：实现Callable接口</h3><ol>
<li><p>创建一个实现Callable的实现类</p>
</li>
<li><p>实现call方法，将此线程需要执行的操作声明在call()中</p>
</li>
<li><p>创建Callable接口实现类的对象</p>
</li>
<li><p>将此Callable接口实现类的对象作为传递到FutureTask构造器中，创建FutureTask的对象</p>
</li>
<li><p>将FutureTask的对象作为参数传递到Thread类的构造器中，创建Thread对象，并调用start()</p>
</li>
<li><p>获取Callable中call方法的返回值</p>
<p>返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1.创建一个实现Callable的实现类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NumThread</span> <span class="keyword">implements</span> <span class="title">Callable</span></span>&#123;</span><br><span class="line">    <span class="comment">//2.实现call方法，将此线程需要执行的操作声明在call()中</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= <span class="number">100</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span>(i % <span class="number">2</span> == <span class="number">0</span>)&#123;</span><br><span class="line">                System.out.println(i);</span><br><span class="line">                sum += i;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadNew</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//3.创建Callable接口实现类的对象</span></span><br><span class="line">        NumThread numThread = <span class="keyword">new</span> NumThread();</span><br><span class="line">        <span class="comment">//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中，创建FutureTask的对象</span></span><br><span class="line">        FutureTask futureTask = <span class="keyword">new</span> FutureTask(numThread);</span><br><span class="line">        <span class="comment">//5.将FutureTask的对象作为参数传递到Thread类的构造器中，创建Thread对象，并调用start()</span></span><br><span class="line">        <span class="keyword">new</span> Thread(futureTask).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//6.获取Callable中call方法的返回值</span></span><br><span class="line">            <span class="comment">//get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。</span></span><br><span class="line">            Object sum = futureTask.get();</span><br><span class="line">            System.out.println(<span class="string">&quot;总和为：&quot;</span> + sum);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ExecutionException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><strong>如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大？</strong></p>
<ol>
<li><p>call()可以有返回值的。</p>
</li>
<li><p>call()可以抛出异常，被外面的操作捕获，获取异常的信息</p>
</li>
<li><p>Callable是支持泛型的</p>
</li>
</ol>
<h3 id="方式4：使用线程池"><a href="#方式4：使用线程池" class="headerlink" title="方式4：使用线程池"></a>方式4：使用线程池</h3><ol>
<li>提供指定线程数量的线程池</li>
<li>执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象</li>
<li>关闭连接池</li>
</ol>
<h4 id="优势"><a href="#优势" class="headerlink" title="优势"></a>优势</h4><ol>
<li><p>提高响应速度（减少了创建新线程的时间）</p>
</li>
<li><p>降低资源消耗（重复利用线程池中线程，不需要每次都创建）</p>
</li>
<li><p>便于线程管理</p>
<p>corePoolSize：核心池的大小</p>
<p>maximumPoolSize：最大线程数</p>
<p>keepAliveTime：线程没有任务时最多保持多长时间后会终止</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">NumberThread</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i &lt;= <span class="number">100</span>;i++)&#123;</span><br><span class="line">            <span class="keyword">if</span>(i % <span class="number">2</span> == <span class="number">0</span>)&#123;</span><br><span class="line">                System.out.println(Thread.currentThread().getName() + <span class="string">&quot;: &quot;</span> + i);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ThreadPool</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//1. 提供指定线程数量的线程池</span></span><br><span class="line">        ExecutorService service = Executors.newFixedThreadPool(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象</span></span><br><span class="line">        service.execute(<span class="keyword">new</span> NumberThread());<span class="comment">//适合适用于Runnable</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//service.submit(Callable callable);//适合使用于Callable</span></span><br><span class="line">        <span class="comment">//3.关闭连接池</span></span><br><span class="line">        service.shutdown();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p><img src= "/img/loading.gif" data-lazy-src="https://www.helloimg.com/images/2021/02/04/image-20210204024756300de5c1cf34a6d7d0a.png" alt="image-20210204024756300de5c1cf34a6d7d0a.png"></p>
<p><img src= "/img/loading.gif" data-lazy-src="https://www.helloimg.com/images/2021/02/04/image-20210204024816814ffd32b74048300e7.png" alt="image-20210204024816814ffd32b74048300e7.png"></p>
<h2 id="二、线程的优先级"><a href="#二、线程的优先级" class="headerlink" title="二、线程的优先级"></a>二、线程的优先级</h2><h3 id="线程的优先级等级"><a href="#线程的优先级等级" class="headerlink" title="线程的优先级等级"></a>线程的优先级等级</h3><ul>
<li>MAX_PRIORITY：10</li>
<li>MIN_PRIORITY：1</li>
<li>NORM_PRIORITY：5</li>
</ul>
<h3 id="涉及的方法"><a href="#涉及的方法" class="headerlink" title="涉及的方法"></a>涉及的方法</h3><ul>
<li>getPriority()：获取线程的优先级</li>
<li>setPriority(int p)：设置线程的优先级</li>
</ul>
<h3 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h3><p>高优先级的线程要抢占低优先级线程cpu的执行权，但是只是从概率上讲，高优先级的线程高概率的情况下被执行。并不意味着只有当高优先级的线程执行完毕以后，低优先级的线程才执行</p>
<h2 id="三、线程的生命周期"><a href="#三、线程的生命周期" class="headerlink" title="三、线程的生命周期"></a>三、线程的生命周期</h2><p><img src= "/img/loading.gif" data-lazy-src="https://www.helloimg.com/images/2021/02/03/image-20210202185449551c05f4dcf561cea3f.png" alt="image-20210202185449551c05f4dcf561cea3f.png"></p>
<p><img src= "/img/loading.gif" data-lazy-src="https://www.helloimg.com/images/2021/02/03/image-202102021855157857501ffdc9e4f785e.png" alt="image-202102021855157857501ffdc9e4f785e.png"></p>
<h2 id="四、线程的安全问题"><a href="#四、线程的安全问题" class="headerlink" title="四、线程的安全问题"></a>四、线程的安全问题</h2><blockquote>
<p>举例：卖票的过程中，出现了重票、错票 —— 线程的安全问题</p>
</blockquote>
<h3 id="1-问题出现的原因"><a href="#1-问题出现的原因" class="headerlink" title="1.问题出现的原因"></a>1.问题出现的原因</h3><p>当多条语句在操作同一个线程共享数据时，一个线程对多条语句只执行了一部分，还没有执行完，另一个线程参与进来执行。导致共享数据的错误。</p>
<h3 id="2-解决办法"><a href="#2-解决办法" class="headerlink" title="2.解决办法"></a>2.解决办法</h3><p>对多条操作共享数据的语句，只能让一个线程都执行完，在执行过程中，其他线程不可以参与执行。</p>
<h3 id="3-在-Java-中，我们通过同步机制，来解决线程的安全问题"><a href="#3-在-Java-中，我们通过同步机制，来解决线程的安全问题" class="headerlink" title="3.在 Java 中，我们通过同步机制，来解决线程的安全问题"></a>3.在 Java 中，我们通过同步机制，来解决线程的安全问题</h3><h4 id="方式一：同步代码块"><a href="#方式一：同步代码块" class="headerlink" title="方式一：同步代码块"></a>方式一：同步代码块</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span>(同步监视器) &#123;</span><br><span class="line">    <span class="comment">// 需要被同步的代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>说明：</p>
<ol>
<li><p>操作共享数据的代码，即为需要被同步的代码   <strong>（ 不能包含代码多了，也不能包含代码少了 ）</strong></p>
</li>
<li><p>共享数据：多个线程共同操作的变量</p>
</li>
<li><p>同步监视器，俗称：锁  ， 任何一个类的对象，都可以充当锁</p>
<p>要求：多个线程必须要共用同一把锁</p>
</li>
</ol>
<p>补充：</p>
<ol>
<li>在实现Runnable接口创建多线程的方式中，我们可以考虑使用this充当同步监视器</li>
<li>在继承Thread类创建多线程的方式中，慎用this来充当同步监视器，考虑使用当前类充当同步监视器</li>
</ol>
<h4 id="方式二：同步方法"><a href="#方式二：同步方法" class="headerlink" title="方式二：同步方法"></a>方式二：同步方法</h4><p>如果操作共享数据的代码完整地声明在一个方法中，我们不妨将此方法声明为同步的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">method</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="comment">// 同步方法的内部代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>总结：</p>
<ol>
<li><p>同步方法仍然涉及到同步监视器，只是我们不需要显式的声明</p>
</li>
<li><p>非静态的同步方法，同步监视器是：this</p>
<p>静态的同步方法，同步监视器是：当前类本身</p>
</li>
</ol>
<h4 id="方式三：Lock锁-——-JDK-5-0-新增"><a href="#方式三：Lock锁-——-JDK-5-0-新增" class="headerlink" title="方式三：Lock锁  —— JDK 5.0 新增"></a>方式三：Lock锁  —— JDK 5.0 新增</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>&#123;</span><br><span class="line">    <span class="comment">// 1.声明ReentrantLock类的对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ReentrantLock lock = <span class="keyword">new</span> ReentrantLock();</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">method</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">// 2.调用该对象的lock()方法</span></span><br><span class="line">        lock.lock;</span><br><span class="line">        <span class="keyword">try</span>&#123;</span><br><span class="line">            <span class="comment">//保证线程安全的代码</span></span><br><span class="line">        &#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">            <span class="comment">// 3.调用解锁方法unlock()</span></span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "/img/loading.gif" data-lazy-src="https://www.helloimg.com/images/2021/02/03/image-202102030249596854fd2bdfe4e43dad7.png" alt="image-202102030249596854fd2bdfe4e43dad7.png"></p>
<hr>
<h4 id="优势-1"><a href="#优势-1" class="headerlink" title="优势"></a>优势</h4><p>同步的方式解决了线程的安全问题</p>
<h4 id="局限性"><a href="#局限性" class="headerlink" title="局限性"></a>局限性</h4><p>操作同步代码时，只能有一个线程参与，其它线程等待。相当于是一个单线程的过程，效率低</p>
<h3 id="4-线程的死锁问题"><a href="#4-线程的死锁问题" class="headerlink" title="4.线程的死锁问题"></a>4.线程的死锁问题</h3><h4 id="解释"><a href="#解释" class="headerlink" title="解释"></a>解释</h4><ul>
<li>不同的线程分别占用对方需要的同步资源不放弃，都在等待对方放弃自己需要的同步资源，就形成了线程的死锁</li>
<li>出现死锁后，不会出现异常，不会出现提示，只是所有的线程都处于阻塞状态，无法继续</li>
</ul>
<h4 id="解决方法"><a href="#解决方法" class="headerlink" title="解决方法"></a>解决方法</h4><ul>
<li>专门的算法、原则</li>
<li>尽量减少同步资源的定义</li>
<li>尽量避免嵌套同步</li>
</ul>
<h2 id="五、线程的通信"><a href="#五、线程的通信" class="headerlink" title="五、线程的通信"></a>五、线程的通信</h2><blockquote>
<p>线程通信的例子：</p>
<p>使用两个线程打印 1-100。线程1、线程2交替打印</p>
</blockquote>
<h3 id="1-涉及到的三个方法"><a href="#1-涉及到的三个方法" class="headerlink" title="1.涉及到的三个方法"></a>1.涉及到的三个方法</h3><ul>
<li>wait()：一旦执行此方法，当前线程就进入阻塞状态，并释放同步监视器</li>
<li>notify()：一旦执行此方法，就会唤醒被wait()的一个线程。如果有多个线程被wait()，就唤醒优先级高的那一个</li>
<li>notifyAll()：一旦执行此方法，就会唤醒所有被wait()的线程</li>
</ul>
<h3 id="2-说明"><a href="#2-说明" class="headerlink" title="2.说明"></a>2.说明</h3><ol>
<li>wait()，notify()，notifyAll()  三个方法必须使用在同步代码块或同步方法中</li>
<li>以上三个方法的调用者，必须是同步代码块或同步方法中的同步监视器，否则会出现<font color="red"> IllegalMonitorStateException </font>异常</li>
<li>以上三个方法定义在 java.lang.Object 类中</li>
</ol>
<h3 id="3-sleep-和wait-的异同"><a href="#3-sleep-和wait-的异同" class="headerlink" title="3.sleep()和wait()的异同"></a>3.sleep()和wait()的异同</h3><h4 id="相同点"><a href="#相同点" class="headerlink" title="相同点"></a>相同点</h4><ol>
<li>一旦执行方法，都可以使得当前线程进入阻塞状态</li>
</ol>
<h4 id="不同点"><a href="#不同点" class="headerlink" title="不同点"></a>不同点</h4><ol>
<li><p>两个方法声明的位置不同：</p>
<p>Thread类中声明sleep() ， Object类中声明wait()</p>
</li>
<li><p>调用的要求不同：</p>
<p>sleep()可以在任何需要的场景下调用，wait()必须使用在同步代码块或同步方法中</p>
</li>
<li><p>关于是否释放同步监视器：</p>
<p>如果两个方法都使用在同步代码块或同步方法中，sleep()不会释放锁，wait()会释放锁</p>
</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Baby李</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2021/02/22/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E5%A4%9A%E7%BA%BF%E7%A8%8B/">http://example.com/2021/02/22/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E5%A4%9A%E7%BA%BF%E7%A8%8B/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">Baby李の小窝</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><a class="post-meta__tags" href="/tags/%E8%AF%AD%E8%A8%80%E7%9B%B8%E5%85%B3/">语言相关</a><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"><div class="social-share" data-image="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/%E6%94%AF%E4%BB%98%E5%AE%9D.png" target="_blank"><img class="post-qr-code-img" data-lazy-src="/img/%E6%94%AF%E4%BB%98%E5%AE%9D.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li><li class="reward-item"><a href="/img/%E5%BE%AE%E4%BF%A1.png" target="_blank"><img class="post-qr-code-img" data-lazy-src="/img/%E5%BE%AE%E4%BF%A1.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/2021/02/22/Java%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80-%E5%BC%82%E5%B8%B8/"><img class="prev-cover" data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Java语言基础:异常</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2021/02/22/Java语言基础-异常/" title="Java语言基础:异常"><img class="cover" data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-02-22</div><div class="title">Java语言基础:异常</div></div></a></div><div><a href="/2021/02/25/Java语言高级-枚举类/" title="Java语言高级-枚举类"><img class="cover" data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-02-25</div><div class="title">Java语言高级-枚举类</div></div></a></div><div><a href="/2021/02/25/Java语言高级-注解/" title="Java语言高级-注解"><img class="cover" data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-02-25</div><div class="title">Java语言高级-注解</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" data-lazy-src="/img/%E5%A4%B4%E5%83%8F.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">Baby李</div><div class="author-info__description">技术小白的博客罢了</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">4</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">3</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">1</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/BabyLy233"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/BabyLy233" target="_blank" title="Github"><i class="iconfont icon-huaban88"></i></a><a class="social-icon" href="mailto:2105451348@qq.com" target="_blank" title="Email"><i class="iconfont icon-mail-back"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-QQ"></i></a><a class="social-icon" href="https://steamcommunity.com/profiles/76561198139459503/" target="_blank" title="Steam个人主页"><i class="iconfont icon-steam"></i></a><a class="social-icon" href="https://music.163.com/#/user/home?id=124240171" target="_blank" title="网易云"><i class="iconfont icon-wangyiyunyinle"></i></a><a class="social-icon" href="https://space.bilibili.com/6466658" target="_blank" title="bilibili个人主页"><i class="iconfont icon-bilibili1"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">小李的个人博客开张啦~</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-number">1.</span> <span class="toc-text">一、多线程的创建</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F1%EF%BC%9A%E7%BB%A7%E6%89%BF%E4%BA%8EThread%E7%B1%BB"><span class="toc-number">1.1.</span> <span class="toc-text">方式1：继承于Thread类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%A4%BA%E4%BE%8B"><span class="toc-number">1.1.1.</span> <span class="toc-text">示例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E4%B8%80"><span class="toc-number">1.1.2.</span> <span class="toc-text">问题一</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%97%AE%E9%A2%98%E4%BA%8C"><span class="toc-number">1.1.3.</span> <span class="toc-text">问题二</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Thread%E7%B1%BB%E4%B8%AD%E7%9A%84%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95"><span class="toc-number">1.2.</span> <span class="toc-text">Thread类中的常用方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F2%EF%BC%9A%E5%AE%9E%E7%8E%B0Runnable%E6%8E%A5%E5%8F%A3"><span class="toc-number">1.3.</span> <span class="toc-text">方式2：实现Runnable接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A5%E4%B8%8A%E4%B8%A4%E7%A7%8D%E6%96%B9%E5%BC%8F%E7%9A%84%E6%AF%94%E8%BE%83"><span class="toc-number">1.4.</span> <span class="toc-text">以上两种方式的比较</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#lt-%E2%80%94%E2%80%94JDK-5-0%E6%96%B0%E5%A2%9E%E7%BA%BF%E7%A8%8B%E5%88%9B%E5%BB%BA%E6%96%B9%E5%BC%8F%E2%80%94%E2%80%94-gt"><span class="toc-number">1.5.</span> <span class="toc-text">&lt;——JDK 5.0新增线程创建方式——&gt;</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F3%EF%BC%9A%E5%AE%9E%E7%8E%B0Callable%E6%8E%A5%E5%8F%A3"><span class="toc-number">1.6.</span> <span class="toc-text">方式3：实现Callable接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F4%EF%BC%9A%E4%BD%BF%E7%94%A8%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="toc-number">1.7.</span> <span class="toc-text">方式4：使用线程池</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%98%E5%8A%BF"><span class="toc-number">1.7.1.</span> <span class="toc-text">优势</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E7%BA%BF%E7%A8%8B%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7"><span class="toc-number">2.</span> <span class="toc-text">二、线程的优先级</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7%E7%AD%89%E7%BA%A7"><span class="toc-number">2.1.</span> <span class="toc-text">线程的优先级等级</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B6%89%E5%8F%8A%E7%9A%84%E6%96%B9%E6%B3%95"><span class="toc-number">2.2.</span> <span class="toc-text">涉及的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B4%E6%98%8E"><span class="toc-number">2.3.</span> <span class="toc-text">说明</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E7%BA%BF%E7%A8%8B%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">3.</span> <span class="toc-text">三、线程的生命周期</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98"><span class="toc-number">4.</span> <span class="toc-text">四、线程的安全问题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E9%97%AE%E9%A2%98%E5%87%BA%E7%8E%B0%E7%9A%84%E5%8E%9F%E5%9B%A0"><span class="toc-number">4.1.</span> <span class="toc-text">1.问题出现的原因</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E8%A7%A3%E5%86%B3%E5%8A%9E%E6%B3%95"><span class="toc-number">4.2.</span> <span class="toc-text">2.解决办法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%9C%A8-Java-%E4%B8%AD%EF%BC%8C%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E5%90%8C%E6%AD%A5%E6%9C%BA%E5%88%B6%EF%BC%8C%E6%9D%A5%E8%A7%A3%E5%86%B3%E7%BA%BF%E7%A8%8B%E7%9A%84%E5%AE%89%E5%85%A8%E9%97%AE%E9%A2%98"><span class="toc-number">4.3.</span> <span class="toc-text">3.在 Java 中，我们通过同步机制，来解决线程的安全问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-number">4.3.1.</span> <span class="toc-text">方式一：同步代码块</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A%E5%90%8C%E6%AD%A5%E6%96%B9%E6%B3%95"><span class="toc-number">4.3.2.</span> <span class="toc-text">方式二：同步方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E5%BC%8F%E4%B8%89%EF%BC%9ALock%E9%94%81-%E2%80%94%E2%80%94-JDK-5-0-%E6%96%B0%E5%A2%9E"><span class="toc-number">4.3.3.</span> <span class="toc-text">方式三：Lock锁  —— JDK 5.0 新增</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%98%E5%8A%BF-1"><span class="toc-number">4.3.4.</span> <span class="toc-text">优势</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%B1%80%E9%99%90%E6%80%A7"><span class="toc-number">4.3.5.</span> <span class="toc-text">局限性</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-%E7%BA%BF%E7%A8%8B%E7%9A%84%E6%AD%BB%E9%94%81%E9%97%AE%E9%A2%98"><span class="toc-number">4.4.</span> <span class="toc-text">4.线程的死锁问题</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E9%87%8A"><span class="toc-number">4.4.1.</span> <span class="toc-text">解释</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95"><span class="toc-number">4.4.2.</span> <span class="toc-text">解决方法</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E7%BA%BF%E7%A8%8B%E7%9A%84%E9%80%9A%E4%BF%A1"><span class="toc-number">5.</span> <span class="toc-text">五、线程的通信</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%B6%89%E5%8F%8A%E5%88%B0%E7%9A%84%E4%B8%89%E4%B8%AA%E6%96%B9%E6%B3%95"><span class="toc-number">5.1.</span> <span class="toc-text">1.涉及到的三个方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E8%AF%B4%E6%98%8E"><span class="toc-number">5.2.</span> <span class="toc-text">2.说明</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-sleep-%E5%92%8Cwait-%E7%9A%84%E5%BC%82%E5%90%8C"><span class="toc-number">5.3.</span> <span class="toc-text">3.sleep()和wait()的异同</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B8%E5%90%8C%E7%82%B9"><span class="toc-number">5.3.1.</span> <span class="toc-text">相同点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%8D%E5%90%8C%E7%82%B9"><span class="toc-number">5.3.2.</span> <span class="toc-text">不同点</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/02/25/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E6%B3%A8%E8%A7%A3/" title="Java语言高级-注解"><img data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java语言高级-注解"/></a><div class="content"><a class="title" href="/2021/02/25/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E6%B3%A8%E8%A7%A3/" title="Java语言高级-注解">Java语言高级-注解</a><time datetime="2021-02-25T13:47:19.000Z" title="发表于 2021-02-25 21:47:19">2021-02-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/02/25/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E6%9E%9A%E4%B8%BE%E7%B1%BB/" title="Java语言高级-枚举类"><img data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java语言高级-枚举类"/></a><div class="content"><a class="title" href="/2021/02/25/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E6%9E%9A%E4%B8%BE%E7%B1%BB/" title="Java语言高级-枚举类">Java语言高级-枚举类</a><time datetime="2021-02-25T13:42:51.000Z" title="发表于 2021-02-25 21:42:51">2021-02-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/02/22/Java%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80-%E5%BC%82%E5%B8%B8/" title="Java语言基础:异常"><img data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java语言基础:异常"/></a><div class="content"><a class="title" href="/2021/02/22/Java%E8%AF%AD%E8%A8%80%E5%9F%BA%E7%A1%80-%E5%BC%82%E5%B8%B8/" title="Java语言基础:异常">Java语言基础:异常</a><time datetime="2021-02-22T14:07:41.000Z" title="发表于 2021-02-22 22:07:41">2021-02-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/02/22/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="Java语言高级:多线程"><img data-lazy-src="https://www.helloimg.com/images/2021/02/22/BcV0c0.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java语言高级:多线程"/></a><div class="content"><a class="title" href="/2021/02/22/Java%E8%AF%AD%E8%A8%80%E9%AB%98%E7%BA%A7-%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="Java语言高级:多线程">Java语言高级:多线程</a><time datetime="2021-02-22T09:53:55.000Z" title="发表于 2021-02-22 17:53:55">2021-02-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 By Baby李</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    let initData = {
      el: '#twikoo-wrap',
      envId: 'my-hexo-9gyfpq4878178bb0',
      region: ''
    }

    if (false) {
      const otherData = false
      initData = Object.assign(initData, otherData)
    }
    
    twikoo.init(initData)
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'my-hexo-9gyfpq4878178bb0',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><div class="aplayer no-destroy" data-id="989088517" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="auto" data-autoplay="true" muted></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/ae682a17.js","daovoice")
</script><script>var isChatBtn = true
daovoice('init', {
  app_id: 'ae682a17',},{
  launcher: { 
     disableLauncherIcon: isChatBtn // 悬浮 ICON 是否显示
  },
});
daovoice('update');

if (isChatBtn) {
  var chatBtnFn = () => {
    var chatBtn = document.getElementById("chat_btn")
    chatBtn.addEventListener("click", function(){
      daovoice('show')
    });
  }
  chatBtnFn()
} else {
  if (false) {
    function chatBtnHide () {
      daovoice('update', {},{
        launcher: { 
        disableLauncherIcon: true // 悬浮 ICON 是否显示
        },
      });
    }
    function chatBtnShow () {
      daovoice('update', {},{
        launcher: { 
        disableLauncherIcon: false // 悬浮 ICON 是否显示
        },
      });
    }
  }
}</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  if (typeof gtag === 'function') {
    gtag('config', '', {'page_path': window.location.pathname});
  }

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})


document.addEventListener('pjax:send', function () {
  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>